import { defineStore } from 'pinia';
import storage from '../utils/storage';
import api from '@/api/api.js';

export const systemStore = defineStore('systemStore', {
  //定义
  state: () => {
    return {
      menu: [],
      routes: [],
      flag: 0,
      collapse: false,
      keepAlive: [],
      userInfo: '' || storage.getItem('userInfo'),
      videoRouter: 'index',
      bookRouter: 'index',
    };
  },
  //计算取值
  getters: {
    getUserInfo(state) {
      return state.userInfo;
    },
    getRoutes(state) {
      api.menu.getRoutes().then(routes => {
        this.routes = routes;
      });
    },
    getVideo(state) {
      return state.videoRouter;
    },
    getBook(state) {
      return state.bookRouter;
    },
  },
  //异步同步方法
  actions: {
    changeVideo(item) {
      this.videoRouter = item;
    },
    changeBook(item) {
      this.bookRouter = item;
    },
    async initRouter() {
      if (!this.routes.length > 0) {
        console.log(this.routes);
        this.routes = await api.menu.getRoutes();
      } else {
        this.routes = await api.menu.getRoutes();
      }
    },
    //添加路由
    async addRouter(router) {
      //判断是否存在 router
      var isExist = true;
      var routes = this.routes;
      for (let index = 0; index < routes.length; index++) {
        if (routes[index].routerPath == router.routerPath) {
          isExist = false;
          break;
        }
      }
      //不存在添加
      if (isExist) {
        this.routes.push(router);
      }
    },
    //重置菜单和路由
    restMenu() {
      api.menu.getSysMenuByAuthority({}).then(data => {
        this.menu = data;
      });
      api.menu.getRoutes().then(routes => {
        this.routes = routes;
      });
    },
  },
  persist: {
    key: 'systemStore',
  },
});
